from typing import Optional

from fastapi import APIRouter
from fastapi_amis_admin.globals.deps import AsyncSess, SyncSess
from fastapi_amis_admin.models import Field

from backend.apps.common import PageParams, PageResult, ApiResult
from .models import SysRole

router = APIRouter()


class RoleQueryParams(PageParams):
    name: Optional[str] = Field(title="角色名")

@router.post("/page")
def page(params: RoleQueryParams, sess: SyncSess):
    offset = (params.page - 1) * params.size
    sql_where = []
    if params and params.name:
        sql_where.append(SysRole.name.contains(params.name))
    query = sess.query(SysRole).where(*sql_where)
    results = query.offset(offset).limit(params.size).all()

    total = query.count()
    return PageResult(page=params.page, size=params.size, total=total, list=results)

@router.get("/detail")
def detail(id:int, sess: SyncSess):
    obj = sess.get(SysRole, id)
    return ApiResult(data=obj)

@router.post("/save")
def save(data:SysRole, sess: SyncSess):
    sess.add(data)
    return ApiResult()

@router.put("/update")
def update(data:SysRole, sess: SyncSess):
    print(dict(data))
    sess.query(SysRole).filter(SysRole.id == data.id).update(dict(data))
    return ApiResult()

@router.delete("/delete")
def delete(id:int, sess: SyncSess):
    sess.query(SysRole).filter(SysRole.id == id).delete()
    return ApiResult()
